package com.xh.wm;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import java.util.List;

public class BlogRepoPageProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);

    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        List<String> links = html.xpath("//div[@class='stream-item']/div/a").links().all();
        page.addTargetRequests(links);
        String title = html.xpath("//div[@class='col-xs-12 col-md-9 side-left']/div/h2/strong/text()").toString();
        page.putField("title", title);
        if (page.getResultItems().get("title") == null) {
            page.setSkip(true);
            // 分页连接
            for (int i = 1; i <= 4; i++) {
                page.addTargetRequest("http://www.itcloud.top/index/40/" + i);
            }
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new BlogRepoPageProcessor())
                .addUrl("http://www.itcloud.top")
                .addPipeline(new MyPipeline())
                .thread(1).run();
    }
}